import os
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
from pathlib import Path

class XlsCsvToLuaConverter:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("XLS/CSV转LUA转换器")
        self.root.geometry("600x400")
        
        self.setup_ui()
        
    def setup_ui(self):
        # 主容器
        main_frame = tk.Frame(self.root, padx=20)
        main_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 转换选项
        option_frame = tk.Frame(main_frame)
        option_frame.pack(fill=tk.X, pady=(5, 10))
        
        tk.Label(option_frame, text="转换选项:", font=("Arial", 9, "bold")).pack(anchor="w")
        
        self.convert_type = tk.StringVar(value="folder")
        tk.Radiobutton(option_frame, text="转换整个文件夹", 
                      variable=self.convert_type, value="folder",
                      command=self.update_ui).pack(side=tk.LEFT, padx=10)
        tk.Radiobutton(option_frame, text="转换单个文件", 
                      variable=self.convert_type, value="file",
                      command=self.update_ui).pack(side=tk.LEFT)
        
        # 输入路径部分
        input_frame = tk.Frame(main_frame)
        input_frame.pack(fill=tk.X, pady=(10,0))
        
        # 红色提示文本（上方）
        hint_frame = tk.Frame(input_frame)
        hint_frame.pack(fill=tk.X)
        
        self.input_hint = tk.Label(hint_frame, width=len("输入路径:"))
        self.input_hint.pack(side=tk.LEFT)
        
        self.input_label = tk.Label(hint_frame, text="请输入文件夹路径", 
                                  fg="red", font=("Arial", 9), anchor="w")
        self.input_label.pack(side=tk.LEFT)
        
        # 输入路径标签和浏览按钮
        input_subframe = tk.Frame(input_frame)
        input_subframe.pack(fill=tk.X, pady=5)
        tk.Label(input_subframe, text="输入路径:").pack(side=tk.LEFT)
        self.input_entry = tk.Entry(input_subframe, width=40)
        self.input_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
        self.input_button = tk.Button(input_subframe, text="浏览...", command=self.select_input)
        self.input_button.pack(side=tk.LEFT)
        
        # 输出路径部分
        output_frame = tk.Frame(main_frame)
        output_frame.pack(fill=tk.X, pady=(15,0))
        
        # 红色提示文本（上方）
        hint_frame_out = tk.Frame(output_frame)
        hint_frame_out.pack(fill=tk.X)
        tk.Label(hint_frame_out, width=len("输出路径:")).pack(side=tk.LEFT)
        tk.Label(hint_frame_out, text="输入LUA的输出目录", 
                fg="red", font=("Arial", 9), anchor="w").pack(side=tk.LEFT)
        
        # 输出路径标签和浏览按钮
        output_subframe = tk.Frame(output_frame)
        output_subframe.pack(fill=tk.X, pady=5)
        tk.Label(output_subframe, text="输出路径:").pack(side=tk.LEFT)
        self.output_entry = tk.Entry(output_subframe, width=40)
        self.output_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
        tk.Button(output_subframe, text="浏览...", command=self.select_output).pack(side=tk.LEFT)
        
        # 文件名格式选项
        format_frame = tk.Frame(main_frame)
        format_frame.pack(fill=tk.X, pady=(15,5))
        tk.Label(format_frame, text="文件名格式:", font=("Arial", 9, "bold")).pack(anchor="w")
        
        self.format_var = tk.StringVar(value="same")
        tk.Radiobutton(format_frame, text="与原文件同名", 
                      variable=self.format_var, value="same").pack(side=tk.LEFT, padx=10)
        tk.Radiobutton(format_frame, text="小写字母", 
                      variable=self.format_var, value="lowercase").pack(side=tk.LEFT)
        
        # 确定按钮
        confirm_frame = tk.Frame(main_frame)
        confirm_frame.pack(side=tk.BOTTOM, pady=15, fill=tk.X)
        tk.Button(confirm_frame, text="开始转换", width=15, command=self.convert_to_lua).pack()
    
    def update_ui(self):
        if self.convert_type.get() == "folder":
            self.input_label.config(text="请输入文件夹路径")
            self.input_button.config(text="选择文件夹...")
        else:
            self.input_label.config(text="请选择XLS/CSV文件")
            self.input_button.config(text="选择文件...")
    
    def select_input(self):
        if self.convert_type.get() == "folder":
            path = filedialog.askdirectory(title="选择输入文件夹")
        else:
            file_types = [("Excel/CSV Files", "*.xls *.xlsx *.csv"), ("All Files", "*.*")]
            path = filedialog.askopenfilename(title="选择XLS/CSV文件", filetypes=file_types)
            
        if path: 
            self.input_entry.delete(0, tk.END)
            self.input_entry.insert(0, path)
    
    def select_output(self):
        path = filedialog.askdirectory(title="选择输出文件夹")
        if path: 
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, path)
    
    def convert_to_lua(self):
        input_path = self.input_entry.get()
        output_path = self.output_entry.get()
        
        if not input_path or not output_path:
            messagebox.showerror("错误", "请选择输入和输出路径")
            return
        
        try:
            if self.convert_type.get() == "folder":
                # 转换整个文件夹
                files = []
                for ext in ('*.xls', '*.xlsx', '*.csv'):
                    files.extend(Path(input_path).glob(ext))
                
                if not files:
                    messagebox.showwarning("警告", "输入路径中没有找到XLS/CSV文件")
                    return
            else:
                # 转换单个文件
                files = [Path(input_path)]
                if not files[0].is_file():
                    messagebox.showwarning("警告", "选择的文件不存在")
                    return
            
            total_files = 0
            for file in files:
                # 读取文件
                if file.suffix == '.csv':
                    df = pd.read_csv(file, header=None, skiprows=2)
                    comments = pd.read_csv(file, header=None, nrows=2)
                else:
                    df = pd.read_excel(file, header=None, skiprows=2)
                    comments = pd.read_excel(file, header=None, nrows=2)
                
                # 生成LUA内容
                lua_content = self.generate_lua(df, comments)
                
                # 确定输出文件名
                if self.format_var.get() == "lowercase":
                    lua_file = file.stem.lower() + '.lua'
                else:
                    lua_file = file.stem + '.lua'
                
                lua_path = Path(output_path) / lua_file
                
                with open(lua_path, 'w', encoding='utf-8') as f:
                    f.write(lua_content)
                
                total_files += 1
            
            messagebox.showinfo("完成", f"成功转换 {total_files} 个文件")
            self.root.destroy()
            
        except Exception as e:
            messagebox.showerror("错误", f"转换过程中发生错误: {str(e)}")
    
    def generate_lua(self, df, comments):
        # 处理注释行
        lua_str = "-- 注释信息:\n"
        for _, row in comments.iterrows():
            lua_str += f"-- {row[0]}\n"
        
        # 处理表头
        headers = df.iloc[0].tolist()
        lua_str += "\nlocal data = {\n"
        
        # 处理数据行，以第一列为key
        for i in range(1, len(df)):
            row = df.iloc[i]
            
            # 跳过空行
            if pd.isna(row[0]):
                continue
                
            key = self.format_lua_value(row[0])
            lua_str += f"    [{key}] = {{\n"
            
            # 处理列数据
            for j in range(len(row)):
                # 跳过空列
                if j >= len(headers) or pd.isna(headers[j]):
                    continue
                    
                val = row[j]
                header = headers[j]
                lua_str += f"        {header} = {self.format_lua_value(val)},\n"
            
            lua_str += "    },\n"
        
        lua_str += "}\n\nreturn data"
        return lua_str
    
    def format_lua_value(self, value):
        if pd.isna(value):
            return "nil"
        if isinstance(value, (int, float)):
            return str(value)
        if isinstance(value, str):
            # 处理Lua特殊字符
            value = value.replace('"', '\\"').replace('\n', '\\n')
            return f'"{value}"'
        return f'"{str(value)}"'

if __name__ == "__main__":
    app = XlsCsvToLuaConverter()
    app.root.mainloop()
